import {
defineStore
} from 'pinia'
import { LoginState } from "/@ts/types/system";
import { getToken, removeToken, setToken } from "/@ts/hooks/cookie";
import { getInfo, login, logout } from "/@ts/axios/urlApi/system";
import getmd5 from '/@ts/plugins/md5';
export const useLoginStore = defineStore('login', {
    state: ():LoginState => ({
      permissions: [],
      isLogin: false,
      token: "",
      roles: [],
      userInfo: {},
    }),
    getters: {
        getPermissions() {
            return this.permissions;
        },
        getIsLogin() {
            return this.isLogin;
        },
        getToken() {
            return this.token;
        },
        getRoles() {
            return this.roles;
        },
        getUserInfo() {
            return this.userInfo;
        }
    },
    actions: {
      SET_PERMISSIONS(permissions: Array<string>) {
        this.permissions = permissions;
      },
      SET_ROLES(roles: Array<string>) {
        this.roles = roles;
      },
      SET_TOKEN(token: string) {
        this.token = token;
      },
      SET_userInfo(userInfo: any) {
        this.userInfo = userInfo;
      },
      setIsLogin(){
        if (getToken()) {
          this.isLogin = true; //登录
        } else {
          this.isLogin = false; //登录
        }
      },
      Login(userInfo: any) {
        return new Promise((resolve, reject) => {
          
          login({
            ...userInfo,
            username: userInfo.username.trim(),
            password: getmd5(userInfo.password)
          })
            .then((res: ResponseConfig) => {
              setToken(res.token);
              this.SET_TOKEN(res.token);
              resolve(res.token);
            })
            .catch((error: Error) => {
              reject(error);
            });
        });
      },
      GetInfo() {
        return new Promise((resolve, reject) => {
          getInfo()
            .then((res: ResponseConfig) => {
              const user = res.user;
              if (res.roles && res.roles.length > 0) {
                // 验证返回的roles是否是一个非空数组
                this.SET_ROLES(res.roles);
                this.SET_PERMISSIONS( res.permissions);
              } else {
                this.SET_ROLES(["ROLE_DEFAULT"]);
              }
              this.SET_userInfo(user);
              resolve(res);
            })
            .catch((error: Error) => {
              reject(error);
            });
        });
      },
      LogOut() {
        return new Promise((resolve, reject) => {
          logout()
            .then(() => {
              this.SET_TOKEN( "");
              this.SET_ROLES([]);
              this.SET_PERMISSIONS([]);
              removeToken();
              resolve("");
            })
            .catch((error: Error) => {
              reject(error);
            });
        });
      }
    }
})